﻿using System.Net.Http.Headers;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;
using YukariToolBox.LightLog;

namespace CommonTools.HttpClient;

/// <summary>
/// http请求
/// </summary>
public class HttpClientHelper
{
    /// <summary>
    /// http请求
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="method">类型</param>
    /// <param name="data">请求参数</param>
    /// <param name="token">token</param>
    /// <returns></returns>
    public static async ValueTask<HttpStatusCode> SendAsync(string url, HttpMethod method, string data = "", string token = "")
    {
        try
        {
            System.Net.Http.HttpClient _httpClient;
            var request = new HttpRequestMessage(method, url);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            if (!string.IsNullOrEmpty(token))
            {
                var handler = new HttpClientHandler() { UseCookies = false };
                _httpClient = new System.Net.Http.HttpClient(handler);
                request.Headers.Add("Authorization", token);
            }
            else
            {
                _httpClient = new System.Net.Http.HttpClient();
            }

            if (!string.IsNullOrEmpty(data))
            {
                request.Content = new StringContent(data, Encoding.UTF8, "application/json");
            }

            var response = await _httpClient.SendAsync(request);
            Log.Info("HttpClientHelper", $"Send: {url}, {data}, Code: {response.StatusCode}");
            return response.StatusCode;
        }
        catch (Exception e)
        {
            var isTimeout = e is TimeoutException;

            //在错误为超时时不打印log
            Log.Error("HttpClientHelper", !isTimeout ? $"ApiSend 发生错误: {e.Message}" : $"API超时[url:{url}]");
            return HttpStatusCode.InternalServerError;
        }

    }

    /// <summary>
    /// http请求
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="method">类型</param>
    /// <param name="data">请求参数</param>
    /// <param name="token">token</param>
    /// <returns></returns>
    public static async ValueTask<(HttpStatusCode, JObject)> SendAsyncRes(string url, HttpMethod method, string data = "", string token = "")
    {
        try
        {
            System.Net.Http.HttpClient _httpClient;
            var request = new HttpRequestMessage(method, url);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            if (!string.IsNullOrEmpty(token))
            {
                var handler = new HttpClientHandler() { UseCookies = false };
                _httpClient = new System.Net.Http.HttpClient(handler);
                request.Headers.Add("Authorization", token);
            }
            else
            {
                _httpClient = new System.Net.Http.HttpClient();
            }

            if (!string.IsNullOrEmpty(data))
            {
                request.Content = new StringContent(data, Encoding.UTF8, "application/json");
            }

            var response = await _httpClient.SendAsync(request);

            string result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            string lastResult = "{data:" + result + "}";
            Log.Info("HttpClientHelper", $"Send: {url}, {data}, Code: {response.StatusCode}, Result: {lastResult}");
            return (response.StatusCode, JObject.Parse(lastResult));
        }
        catch (Exception e)
        {
            var isTimeout = e is TimeoutException;

            //在错误为超时时不打印log
            Log.Error("HttpClientHelper", !isTimeout ? $"ApiSend 发生错误: {e.Message}" : $"API超时[url:{url}]");
            return (HttpStatusCode.InternalServerError, new JObject());
        }

    }

    /// <summary>
    /// http请求
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="method">类型</param>
    /// <param name="data">请求参数</param>
    /// <param name="token">token</param>
    /// <param name="contentType">contentType</param>
    /// <returns></returns>
    public static async ValueTask<HttpStatusCode> SendAsync(string url, HttpMethod method, string data, string token = "", string contentType = "")
    {
        try
        {
            System.Net.Http.HttpClient _httpClient;
            var request = new HttpRequestMessage(method, url);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
            if (!string.IsNullOrEmpty(token))
            {
                var handler = new HttpClientHandler() { UseCookies = false };
                _httpClient = new System.Net.Http.HttpClient(handler);
                request.Headers.Add("Authorization", token);
            }
            else
            {
                _httpClient = new System.Net.Http.HttpClient();
            }
            byte[] bytes = await File.ReadAllBytesAsync(data);
            request.Content = new ByteArrayContent(bytes);


            var response = await _httpClient.SendAsync(request);
            Log.Info("HttpClientHelper", $"Send: {url}, {data}, Code: {response.StatusCode}");

            return response.StatusCode;
        }
        catch (Exception e)
        {
            var isTimeout = e is TimeoutException;

            //在错误为超时时不打印log
            Log.Error("HttpClientHelper", !isTimeout ? $"ApiSend 发生错误: {e.Message}" : $"API超时[url:{url}]");
            return HttpStatusCode.InternalServerError;
        }

    }

    /// <summary>
    /// http请求
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="method">类型</param>
    /// <param name="data">请求参数</param>
    /// <param name="token">token</param>
    /// <returns></returns>
    public static async ValueTask<HttpStatusCode> SendAsyncForm(string url, HttpMethod method, string data, string token = "")
    {
        try
        {
            System.Net.Http.HttpClient _httpClient;
            var request = new HttpRequestMessage(method, url);
            if (!string.IsNullOrEmpty(token))
            {
                var handler = new HttpClientHandler() { UseCookies = false };
                _httpClient = new System.Net.Http.HttpClient(handler);
                request.Headers.Add("Authorization", token);
            }
            else
            {
                _httpClient = new System.Net.Http.HttpClient();
            }

            using var content = new MultipartFormDataContent();
            var dataByteArrayContent = new ByteArrayContent(Encoding.UTF8.GetBytes(data));
            dataByteArrayContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "payload_json"
            };
            content.Add(dataByteArrayContent);
            request.Content = content;

            var response = await _httpClient.SendAsync(request);
            //string result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            Log.Info("HttpClientHelper", $"Send: {url}, {data}, Code: {response.StatusCode}");
            return response.StatusCode;
        }
        catch (Exception e)
        {
            var isTimeout = e is TimeoutException;

            //在错误为超时时不打印log
            Log.Error("HttpClientHelper", !isTimeout ? $"ApiSend 发生错误: {e.Message}" : $"API超时[url:{url}]");
            return HttpStatusCode.InternalServerError;
        }

    }

    /// <summary>
    /// http请求
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <returns></returns>
    public static async ValueTask<(HttpStatusCode, Stream)> SendAsync(string url)
    {
        try
        {
            System.Net.Http.HttpClient _httpClient = new System.Net.Http.HttpClient(); ;
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            var response = await _httpClient.SendAsync(request);
            Stream stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
            return (response.StatusCode, stream);
        }
        catch (Exception e)
        {
            var isTimeout = e is TimeoutException;

            //在错误为超时时不打印log
            if (!isTimeout)
                Log.Error("HttpClientHelper", $"ApiSend 发生错误: {e.Message}");
            else
            {
                Log.Error("HttpClientHelper", $"API超时[url:{url}]");
            }
            return (HttpStatusCode.InternalServerError, null)!;
        }

    }
}